﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using jSLApp.Client.ApplicationBase;
using jSLApp.Client.MainService;
using jSLCore.Client.Presentation.BaseControl;
using jSLCore.Client.Presentation.BaseControl.DialogMessage;
using jSLCore.Client.Utility;
using jSLCore.Utility.Extensions;

namespace jSLApp.Client.Forms
{
    /// <summary>
    /// creating Article
    /// </summary>
    public partial class NewArticle : DialogControl
    {
        public NewArticle()
        {
            InitializeComponent();
        }

        #region dialog

        public override void OkClicked()
        {
            byte[] bs = null;
            try
            {
                var stream = file.OpenRead();
                bs = new byte[stream.Length];
                stream.Read(bs, 0, (int) stream.Length);
                stream.Close();
            }
            catch(IOException)
            {
                ErrorBox.ShowDialog("Не удалось прочесть файл статьи");
                   return; 
            }
            
            DoWork("Создание статьи",(sender, args) =>
                                         {
                                             args.Result = Communication.Proxy.CreateArticle(args.String, (string) args.Params[1],
                                                                               (byte[]) args.Params[2],
                                                                               (ArticleType) args.Params[3],
                                                                               (byte[]) args.Params[4],
                                                                               (string) args.Params[5]);
                                         },(o, eventArgs) =>
                                               {
                                                   if(eventArgs.Error==null)
                                                   {
                                                       var dlg = new InfoBox("Статья создана",2000);
                                                       dlg.ShowDialog((sender, data) => InvokeDataSelected(eventArgs.Result));
                                                   }
                                               }, briefTxt.Text, headerTxt.Text, Image, Enum.Parse(typeof(ArticleType), ((ComboBoxItem)typeCombo.SelectedItem).Tag.ToString(), true), bs, file.Extension.Trim('.'));
        }

        public override bool IsOkVisible
        {
            get { return true; }
        }

        public override bool IsStandartOkCancelEnabled
        {
            get { return true; }
        }

        public override object OkContent
        {
            get { return "Опубликовать"; }
        }
        
        public override bool AutoSize
        {
            get { return true; }
        }

        public override void LoadInitialData()
        {
            CheckCustomError();
            DoWork("Загрузка NoPhoto",(sender, args) =>
                                          {
                                              args.Result = Communication.Proxy.GetNoPhotoImage();
                                          },(o, eventArgs) =>
                                                                {
                                                                    if(eventArgs.Error==null)
                                                                    {
                                                                        img.Source =
                                                                            ((byte[]) eventArgs.Result).
                                                                                ConvertToImageSource();
                                                                    }
                                                                });
        }

        private byte[] Image;
        private FileInfo file;

        private void CheckCustomError()
        {
            if(Image==null)
            {
                CustomError = "Необходимо указать изображение";
                return;
            }
            if(file==null)
            {
                CustomError = "Необходимо указать архив htm";
                return;
            }
            CustomError = string.Empty;
        }

        public override Control GetControlForInitialFocus()
        {
            return headerTxt;
        }

        #endregion

        private void pointImage_Clicked(object sender, MouseButtonEventArgs e)
        {
            var dlg = new OpenFileDialog();
            if(dlg.ShowDialog().GetValueOrDefault(false))
            {
                var stream = dlg.File.OpenRead();
                byte[] bs = new byte[stream.Length];
                stream.Read(bs, 0, (int) stream.Length);
                stream.Close();

                DoWork("Проверка изображения",(o, args) =>
                                                  {
                                                      args.Result =
                                                          Communication.Proxy.ConvertImageToPng150x150(
                                                              (byte[]) args.Argument);
                                                  },(sender1, eventArgs) =>
                                                                   {
                                                                       if(eventArgs.Error==null)
                                                                       {
                                                                           img.Source =
                                                                               ((byte[])eventArgs.Result).ConvertToImageSource();
                                                                           Image = (byte[]) eventArgs.Result;
                                                                           CheckCustomError();
                                                                       }
                                                                   },(object)bs);

            }
        }
        
        private void pointToHTML(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog();
            if(dlg.ShowDialog().GetValueOrDefault(false))
            {
                file = dlg.File;
                archiveLink.Content = dlg.File.Name;
                CheckCustomError();
            }
        }
    }
}
